$(function () {
    //销售单位加载
    $('#nbxsd_xsdw').combotree({
        loadFilter: function (rows) {
            return convert(rows);
        },
        onSelect: function (record) {
            $('#nbxsd_xsry').combobox({
                url: $.webPath() + '/sys/yg/ygXmList?zgjgId=' + record.id,
                valueField: 'id',
                textField: 'xm'
            });
        }
    });

    //客户加载
    $("[name='nbxsd_kh']").jgbmtree($("[name='nbxsd_khbm']"), '', '', '');

    var options = getXsdGridOption();
    $('#nbxsd-grid').datagrid(options);
})

function nbxsd_search() {
    var zt = $("#nbxsd-toolbar input[name='nbxsd_zt']").val();
    var xsdh = $("#nbxsd-toolbar input[name='nbxsd_xsdh']").val();
    var kh = $("#nbxsd-toolbar input[name='nbxsd_kh']").val();
    var khbm = $("#nbxsd-toolbar input[name='nbxsd_khbm']").val();
    var xsdw = $("#nbxsd-toolbar input[name='nbxsd_xsdw']").val();
    var xsr = $("#nbxsd-toolbar input[name='nbxsd_xsry']").val();
    var gc = $("#nbxsd-toolbar input[name='xsd_gc']").val();
    var fhsjStart = $('#nbxsd_fhrq_start').datebox('getValue');
    var fhsjEnd = $('#nbxsd_fhrq_end').datebox('getValue');
    var options = $.extend(getXsdGridOption(),
        {queryParams: {zt: zt, xsdh: xsdh, khId: kh, khbmId: khbm, xsdwId: xsdw, xsrId: xsr, gcId: gc, fhsjStart: fhsjStart, fhsjEnd: fhsjEnd}});
    $('#nbxsd-grid').datagrid(options);
}

function nbxsd_addItem(title, action) {
    var href = $.webPath() + "/xsgl/nbxsd/nbxsd_content";
    xsdhref = $.webPath() + "/xsgl/nbxsd/" + action;
    xsd_showDialog(title, href);
}

function nbxsd_editItem(title, action) {
    var record = $("#nbxsd-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的记录!", "info");
        return;
    }
    var href = $.webPath() + "/xsgl/nbxsd/nbxsd_content?xsdId=" + record.id;
    xsdhref = $.webPath() + "/xsgl/nbxsd/" + action;
    xsd_showDialog(title, href);
}

//新增、修改销售单弹出界面
var nbxsd_win;
function xsd_showDialog(title, href) {

    var button = [
        {text: '保存', handler: xsd_saveItem}
    ];

    nbxsd_win = $.window({
        title: title,
        iconCls: 'icon-add2',
        url: href,
        width: 1024,
        height: 505,
        buttons: button
    });
}


function xsd_saveItem() {
    var xsfy = $("#xsd_xsfy").val();
    $("#nbxsd_mx").edatagrid('saveRow');
    $("#nbxsd_fy").edatagrid('saveRow');
    $('#nbxsdForm').tabs('select', "销售信息");
    $("#nbxsdForm").form('submit', {
        url: xsdhref,
        onSubmit: function (param) {
            var data = $('#nbxsd_mx').edatagrid("getData");
            var fydata = $('#nbxsd_fy').edatagrid("getData");
            if (!data.rows.length) {
                $('#nbxsdForm').tabs('select', "销售明细");
                $.messager.alert("提示", "请填写销售明细!", "waring");
                return false;
            }
//            if ($("[name='xsd.xslx']").val() == "kcls" && $("#xsd_lj_id").length > 0) {
//                var xtsl = $("#xsd_lj_sl").val();
//                var sumsl = 0;
//                for (var i = 0; i < data.rows.length; i++) {
//                    var sl = parseFloat(data.rows[i]['sbsl']);
//                    sl = isNaN(sl) ? 0 : sl;
//                    sumsl += sl;
//                }
//                if (sumsl > xtsl) {
//                    $.messager.alert("提示", "库存零售数量不得大于路径设定数量!", "waring");
//                    return false;
//                }
//            }

            if (xsfy == '我方承担销售费用') {
                if (!fydata.rows.length) {
                    $('#nbxsdForm').tabs('select', "费用明细");
                    $.messager.alert("提示", "请填写销售费用!", "waring");
                    return false;
                }
            }
            var arrayPrefix = 'xsd.xsmxList';
            var fyPrefix = 'xsd.xsfyList';

            var kcentiry = {};
            var paramString = "{";
            for (var i = 0; i < data.rows.length; i++) {
                var obj = data.rows[i];
                if (obj['kh.id'] == undefined) {
                    $('#nbxsdForm').tabs('select', "销售明细");
                    $.messager.alert("提示", "请选择卡号!", "waring");
                    return false;
                } else {
                    var sl = 0;
                    if (kcentiry['s' + obj['kh.id']] != null) {
                        sl = parseFloat(kcentiry['s' + obj['kh.id']]) - parseFloat(obj['sbsl'].toString());
                    } else {
                        sl = parseFloat(obj['kkdsl'].toString()) - obj['sbsl'];
                    }
                    if (sl >= 0) {
                        kcentiry['s' + obj['kh.id']] = sl;
                    } else {
                        $('#nbxsdForm').tabs('select', "销售明细");
                        $.messager.alert("提示", "库存不够!", "waring");
                        return false;
                    }
                }
                var objectString = $.toJSONStringSubPrefix(obj, arrayPrefix + "[" + i + "].", ['jzfs.id', 'jzfs.z', 'hsj', 'bhsj', 'bz', 'sbsl', 'js', 'kh.id', 'xscb',
                    ['wzgg.id', 'jtwz.id'],
                    ['wzgg.code', 'jtwz.code'],
                    ['wzgg.name', 'jtwz.name'],
                    ['wzgg.ggxh', 'jtwz.ggxh'],
                    ['wzgg.dw', 'jtwz.dw']]);
                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
            }
            //费用物资计划
            for (var i = 0; i < fydata.rows.length; i++) {
                {
                    var objectString = $.toJSONStringPrefix(fydata.rows[i], fyPrefix + "[" + i + "].");
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            if (data.rows && data.rows.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success: function (data) {
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $(nbxsd_win).window('close');
                $('#nbxsd-grid').datagrid('reload');
                $('#nbxsd_layout').layout('panel', 'center').panel('refresh');
                $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
            } else {
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

function nbxsd_destroyItem() {
    var row = $('#nbxsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认删除此销售单', function (r) {
            if (r) {
                var index = $('#nbxsd-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/xsgl/nbxsd/delete_xsd', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200')
                        $('#nbxsd-grid').datagrid('deleteRow', index);
                    else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要删除的销售单", 'info');
    }
}

function nbxsd_commitItem() {
    var row = $('#nbxsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认提交此销售单', function (r) {
            if (r) {
                $.post($.webPath() + '/xsgl/nbxsd/commit_xsd', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200')
                        $('#nbxsd-grid').datagrid('reload');
                    else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要删除的销售单", 'info');
    }
}

function nbxsd_cancelItem() {
    var row = $('#nbxsd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否取消提交此销售单', function (r) {
            if (r) {
                $.post($.webPath() + '/xsgl/nbxsd/cancel_xsd', {xsdId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200')
                        $('#nbxsd-grid').datagrid('reload');
                    else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要取消提交的销售单", 'info');
    }
}


function getXsdGridOption() {
    var options = {
        url: $.webPath() + "/xsgl/nbxsd/xsdList?sftzd=false",
        toolbar: "#nbxsd-toolbar",
        fitColumns: true,
        singleSelect: true,
        pageNumber: 1,
        pagination: true,
        fit: true,
        rownumbers: true,
        onLoadSuccess: function () {
            $("#nbxsd-del").css('display', 'none');
            $("#nbxsd-edit").css('display', 'none');
            $("#btn_commit_nbxsd").css('display', 'none');
            $(this).datagrid('selectRow', 0);
        },
        loadFilter: function (data) {
            $.each(data.rows, function () {
                if (this.zt) {
                    this.zt = this.zt == 'yly' ? "已完结" : this.zt == 'yjs' ? "已结算" : this.zt == 'yzz' ? "已终止" : this.zt == 'ytj' ? "已提交" : this.zt == 'ysp' ? "已审批" : "已保存";
                }
            })
            return data;
        },
        onSelect: function (rowIndex, rowData) {
            if (!rowData) {
                $("#nbxsd-edit").css('display', 'none');
                $("#nbxsd-del").css('display', 'none');
                $("#btn_commit_nbxsd").css('display', 'none');
                $("#btn_cancel_xsd").hide();
                $('#nbxsd_layout').layout('remove', 'center');
                return;
            }
            if (rowData && rowData.zt == '已保存') {
                $("#nbxsd-edit").css('display', '');
                $("#nbxsd-del").css('display', '');
                $("#btn_commit_nbxsd").css('display', '');
                $("#btn_cancel_xsd").hide();
            } else if (rowData && rowData.zt == '已提交') {
                $("#nbxsd-edit").css('display', 'none');
                $("#nbxsd-del").css('display', 'none');
                $("#btn_commit_nbxsd").css('display', 'none');
                $("#btn_cancel_xsd").show();
            } else {
                $("#nbxsd-edit").css('display', 'none');
                $("#nbxsd-del").css('display', 'none');
                $("#btn_commit_nbxsd").css('display', 'none');
                $("#btn_cancel_xsd").hide();
            }
        }, onDblClickCell: function (index, field) {
            if (field == "xsdh") {
                $("#nbxsd-edit:visible").click();
            }
        }
    }

    var columns = {columns: [
        [
            {field: 'xsdh', title: '销售单号', width: 50, formatter: nbxsdCell},
            {field: 'xslx', title: '销售类型', formatter: function (value) {
                if (value == 'nbxs')
                    return '内部销售';
            }, width: 30},
            {field: 'fhsj', title: '发货日期', width: 35},
            {field: 'sxsj', title: '制单日期', width: 35},
            {field: 'kh_jc', title: '采购公司', width: 50},
            {field: 'khbm_jc', title: '采购部门', width: 50},
            {field: 'xssl', title: '销售数量', width: 50,
                formatter: function (value) {
                    var sl = formatSlForHtml(value);
                    return sl;
                }
            },
            {field: 'xsje', title: '销售金额(元)', width: 60,
                formatter: function (value) {
                    var sl = formatJeForHtml2(value);
                    return sl;
                }
            },
            {field: 'fyzr_z', title: '配送类型', width: 25},
            {field: 'gylfyje', title: '配送费用(元)', width: 40,
                formatter: function (value) {
                    var sl = formatJeForHtml2(value);
                    return sl;
                }
            },
            {field: 'xsgs_jc', title: '销售公司', width: 30},
            {field: 'sbgs_jc', title: '申报公司', width: 25},
            {field: 'sbbm_jc', title: '申报部门', width: 25},
            {field: 'sbr_xm', title: '申报人', width: 20},
            {field: 'zt', title: '状态', width: 20}
        ]
    ]}
    options = $.extend(options, columns);
    return options;
}